/*
 *************************************************************************
 *西瑞克斯研发管理系统
 *版 本: 1.0   
 *日 期：02/11/2012    
 *作 者： 王浩 QQ：873987060   
 *************************************************************************   
 */
package com.manager.commons;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginFilter implements Filter {
	protected FilterConfig filterConfig;
	private String loginPage;

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = arg0;
		loginPage = arg0.getInitParameter("loginPage");
		if (loginPage == null)
		{
			throw new ServletException("loginPage init param missing");
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String url = req.getRequestURL().toString();
		if (url.indexOf("login") < 0) {
			if (req.getSession().getAttribute("loginUser") != null) { // 检查是否登录
				chain.doFilter(request, response);
			} else {
				req.getRequestDispatcher(loginPage).forward(request, response); // 如果没有登录，把视图派发到登录页面
				return;
			}
		} else {
			chain.doFilter(request, response);
			return;
		}

	}

	public void destroy() {

	}

}
